﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Elmah;
using SportsStore.Logging;
using SportsStore.Web.Filters;
using SportsStore.Web.Logging;
using SportsStore.Web.Models.Error;
using SportsStore.Web.Models.User;

namespace SportsStore.Web.Controllers
{
    [GetCookieUserFilter]
    public partial class BaseController : Controller
    {
        public BaseController(ILogger logger)
        {
            Logger = logger;
        }

        protected ILogger Logger { get; set; }

        protected override void OnException(ExceptionContext filterContext)
        {
          // Bail if we can't do anything; app will crash.
          if (filterContext == null)
            return;
          if (!filterContext.HttpContext.IsCustomErrorEnabled) return;
          var ex = filterContext.Exception ?? new Exception("No further information exists.");
          filterContext.ExceptionHandled = true;
          if ((ex.GetType() != typeof(HttpRequestValidationException)))
          {
            Logger.Error(ex, filterContext.HttpContext.Request.Path, filterContext.HttpContext.Request.RawUrl);
            var data = new ErrorViewData
            {
              ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
              TheException = ex,
              ShowMessage = filterContext.Exception != null,
              ShowLink = false
            };
            filterContext.Result = View("Error", data);
          }
        }

        private void LogExceptionToElmah(Exception exception)
        {
            HttpContext context = System.Web.HttpContext.Current;
            ErrorLog.GetDefault(context).Log(new Error(exception, context));
            Exception logException = exception;
            while (logException != null)
            {
                Logger.Error(exception.BuildExceptionMessage(new WebMessageInformation()), logException);
                logException = exception.InnerException;
            }
        }

        protected bool IsLoggedInUser(UserViewModel user)
        {
            return (user != null && user.IsLoggedIn);
        }
    }
}